// router/getMenu.js
// import menus from './menus'

// const checkedKeys = ['0-0', '0-1-0', '0-2-1', '0-3-1']
// ['0-0', '0-1', '0-1-0', '0-2', '0-2-1', '0-3']
export function getMenu(menus, checkedKeys) {
  console.log(checkedKeys);
  // 1.想办法获取到 ['0-0', '0-1', '0-1-0', '0-2', '0-2-1', '0-3']
  // 先获取到所有的一级菜单， 合并原来的数组，再去重
  const arr = [];
  checkedKeys.forEach((item) => {
    arr.push(item.slice(0, 3));
  }); // ['0-0', '0-1', '0-2', '0-3']
  // 合并数组，并且去重
  const lastArr = Array.from(new Set([...arr, ...checkedKeys]));
  // ['0-0', '0-1', '0-1-0', '0-2', '0-2-1', '0-3']
  console.log(lastArr);
  // 2.遍历lastArr，组合数据
  const result = [];
  lastArr.forEach((item) => {
    // 2.1获取真实对应的索引值
    const index1 = item.split('-')[1];
    const index2 = item.split('-')[2];
    let obj = {};
    // 2.2 如果index2存在，一定有二级菜单，如果不存在, 判断index1对应的数据存在不存在
    if (index2 >= 0) {
      // 2.4 先构建一级菜单的数据
      obj = {
        title: menus[index1].title,
        path: menus[index1].path,
        key: menus[index1].key,
        icon: menus[index1].icon,
        redirect: menus[index1].redirect,
        children: []
      };
      // 2.5
      const cindex = result.findIndex((item) => item.key === obj.key);
      if (cindex === -1) {
        // 添加二级菜单
        obj.children.push({
          title: menus[index1].children[index2].title,
          path: menus[index1].children[index2].path,
          key: menus[index1].children[index2].key,
          icon: menus[index1].children[index2].icon,
          component: menus[index1].children[index2].component
        });
        result.push(obj);
      } else {
        if (menus[index1].children && menus[index1].children[index2]) {
          // 给既有的一级菜单添加二级菜单
          result[cindex].children.push({
            title: menus[index1].children[index2].title,
            path: menus[index1].children[index2].path,
            key: menus[index1].children[index2].key,
            icon: menus[index1].children[index2].icon,
            component: menus[index1].children[index2].component
          });
        }
      }
    } else {
      // 2.3 先构建一级菜单的数据
      obj = {
        title: menus[index1].title,
        path: menus[index1].path,
        key: menus[index1].key,
        icon: menus[index1].icon,
        component: menus[index1].component,
        children: []
      };
      // 判断数据中有没有obj对应的数据，如果没有，则插入，如果有，不做操作
      !result.some((item) => item.key === obj.key) && result.push(obj);
    }
  });
  // console.log(result)
  return result;
}
